const STORAGE_KEYS = {
  TOKEN: 'token',
  USER_INFO: 'user_info',
  CART: 'cart_items',
  SETTINGS: 'app_settings',
  FIRST_LAUNCH: 'first_launch'
}

export const storage = {
  // Token相关
  setToken(token) {
    uni.setStorageSync(STORAGE_KEYS.TOKEN, token)
  },
  
  getToken() {
    return uni.getStorageSync(STORAGE_KEYS.TOKEN)
  },
  
  removeToken() {
    uni.removeStorageSync(STORAGE_KEYS.TOKEN)
  },
  
  // 用户信息相关
  setUserInfo(userInfo) {
    uni.setStorageSync(STORAGE_KEYS.USER_INFO, JSON.stringify(userInfo))
  },
  
  getUserInfo() {
    const info = uni.getStorageSync(STORAGE_KEYS.USER_INFO)
    return info ? JSON.parse(info) : null
  },
  
  removeUserInfo() {
    uni.removeStorageSync(STORAGE_KEYS.USER_INFO)
  },
  
  // 购物车相关
  setCartItems(items) {
    uni.setStorageSync(STORAGE_KEYS.CART, JSON.stringify(items))
  },
  
  getCartItems() {
    const items = uni.getStorageSync(STORAGE_KEYS.CART)
    return items ? JSON.parse(items) : []
  },
  
  removeCartItems() {
    uni.removeStorageSync(STORAGE_KEYS.CART)
  },
  
  // 设置相关
  setSettings(settings) {
    uni.setStorageSync(STORAGE_KEYS.SETTINGS, JSON.stringify(settings))
  },
  
  getSettings() {
    const settings = uni.getStorageSync(STORAGE_KEYS.SETTINGS)
    return settings ? JSON.parse(settings) : {}
  },
  
  // 首次启动
  setFirstLaunch(value) {
    uni.setStorageSync(STORAGE_KEYS.FIRST_LAUNCH, value)
  },
  
  isFirstLaunch() {
    return uni.getStorageSync(STORAGE_KEYS.FIRST_LAUNCH) !== false
  },
  
  // 通用方法
  set(key, value) {
    uni.setStorageSync(key, typeof value === 'object' ? JSON.stringify(value) : value)
  },
  
  get(key, defaultValue = null) {
    const value = uni.getStorageSync(key)
    if (value === '') return defaultValue
    try {
      return JSON.parse(value)
    } catch {
      return value || defaultValue
    }
  },
  
  remove(key) {
    uni.removeStorageSync(key)
  },
  
  clear() {
    uni.clearStorageSync()
  }
}

export default storage